--#include "data\config\activityconfig\CrossActivity\CrossLeagueMatchesConfig.lua" once
--#include "data\functions\Common\RankMgr.lua" once 		--排行榜管理

CROSS_LEAGUE_IDX   		= 0 				--此副本是第几个擂台
CROSS_LEAGUE_PlAYER1  	= 1
CROSS_LEAGUE_SCORE1   	= 2
CROSS_LEAGUE_PlAYER2  	= 3
CROSS_LEAGUE_SCORE2   	= 4

CROSS_LEAGUE_WIN = 1
CROSS_LEAGUE_LOSE = 2
CROSS_LEAGUE_DRAW = 3

CROSS_LEAGUE_PLAYER_NUM = 2

--是否在联赛副本中
function IsInCrossLeagueFuben(sysarg)
	--print("Actor.getFubenId( sysarg ) ="..Actor.getFubenId( sysarg ))
	if Actor.getFubenId( sysarg ) == CrossLeagueMatchesCfg.fubenId then
		return true
	end
	return false
end

--联赛是否开始
function IsCrossLeagueMatchesStart()
	local sVar = System.getStaticVar()
	if sVar.crossLeagueMatchesStart == 1 then
		return true
	end
	return false
end

--是否可以报名
function IsCrossLeagueMatchesCanSign()
	local sVar = System.getStaticVar()
	if sVar.crossLeagueMatchesSign == 1 then
		return true
	end
	return false
end

--是否可以领取奖励
function IsCrossLeagueMatchesCanGetAward()
	local sVar = System.getStaticVar()
	if sVar.crossLeagueMatchesAward == 1 then
		return true
	end
	return false
end

--联赛开始，清除旧数据
function CrossLeagueMatchesClear()
	local week = System.getDayOfWeek()
	local sVar = System.getStaticVar()
	gRankMgr_Clear(RANK_CROSS_LEAGUE_SIGN)
	if week == 4 then
		gRankMgr_Clear(RANK_CROSS_LEAGUE_SCORE)
		
		sVar.crossLeagueMatchesStart = 1
		sVar.crossLeagueMatchesAward = nil

		if Lang.ScriptTips.CrossLeaguematches006 ~= "" then
			System.broadcastTipmsg( Lang.ScriptTips.CrossLeaguematches006, ttScreenCenter + ttChatWindow )
		end
	elseif not sVar.crossLeagueMatchesStart then
		sVar.crossLeagueMatchesStart = 1
		if Lang.ScriptTips.CrossLeaguematches006 ~= "" then
			System.broadcastTipmsg( Lang.ScriptTips.CrossLeaguematches006, ttScreenCenter + ttChatWindow )
		end
	end
end

--开启报名并广播
function CrossLeagueMatchesSignBroad()
	if not IsCrossLeagueMatchesStart() then return end
	if Lang.ScriptTips.CrossLeaguematches001 ~= "" then
		System.broadcastTipmsg( Lang.ScriptTips.CrossLeaguematches001, ttScreenCenter + ttChatWindow )
	end
	local sVar = System.getStaticVar()
	sVar.crossLeagueMatchesSign = 1
end

--结束报名并广播
function CrossLeagueMatchesSignClose()
	if not IsCrossLeagueMatchesStart() then return end
	if Lang.ScriptTips.CrossLeaguematches002 ~= "" then
		System.broadcastTipmsg( Lang.ScriptTips.CrossLeaguematches002, ttScreenCenter + ttChatWindow )
	end
	local sVar = System.getStaticVar()
	sVar.crossLeagueMatchesSign = nil
end

--玩家随机方法
function GetCrossLeagueMatchesRandomNumber(nStart, nEnd)
	local numTable = {}
	local stateTable = {}
	local nLen = nEnd - nStart + 1
	for idx = nStart,  nEnd do
		local num = System.getRandomNumber(nLen) + 1
		local NewNum = num + nStart - 1
		while stateTable[num] do
			num = num + 1
			NewNum = NewNum + 1
			if num > nLen then
				num = num - nLen
				NewNum = NewNum - nLen
			end
		end
		table.insert(numTable, NewNum)
		stateTable[num] = 1
	end
	return numTable
end

--联赛pk正式开始
function CrossLeagueMatchesStart()
	if not IsCrossLeagueMatchesStart() then return end
	local rankPtr = Ranking.getRanking(RankList[RANK_CROSS_LEAGUE_SIGN].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	--print("rankCount ="..rankCount)
	local needFubenCount = math.floor(rankCount / CROSS_LEAGUE_PLAYER_NUM)
	local dVar = System.getDyanmicVar()
	--if not dVar.crossLeague then
		dVar.crossLeague = {}
	--end
	for idx = 1, needFubenCount do
		local fubenHandle = Fuben.createFuBen( CrossLeagueMatchesCfg.fubenId )
		--print("fubenHandle = "..fubenHandle)
		local fubenPtr = Fuben.getFubenPtr( fubenHandle )
		dVar.crossLeague[idx] = fubenHandle
		Fuben.setActivityType( fubenPtr, enFubenActivityType_CrossLeague )
		Fuben.setFbValue( fubenPtr, CROSS_LEAGUE_IDX, idx )
	end

	local fubenIdx = 1
	local side = 1
	for ii = 1, #CrossLeagueMatchesCfg.ChoiceRankRange do
		local nStart
		if ii == 1 then
			nStart = 1
		else
			nStart = CrossLeagueMatchesCfg.ChoiceRankRange[ii - 1] + 1
		end
		local nEnd = CrossLeagueMatchesCfg.ChoiceRankRange[ii]
		if nEnd > rankCount then
			nEnd = rankCount
		end
		if nEnd < nStart then
			break
		end
		--print("nStart = "..nStart)
		--print("nEnd = "..nEnd)
		local dataTable = GetCrossLeagueMatchesRandomNumber(nStart, nEnd)
		for iii=1, #dataTable do
			--print("dataTable[iii] ="..dataTable[iii])
			local item = Ranking.getItemFromIndex(rankPtr, dataTable[iii] - 1)
			if item then		--当前榜
				local playerId  = tonumber(Ranking.getId(item))
				--print("playerId ="..playerId)
				local player 	= Actor.getActorById( playerId )
				if player then 		--玩家必须在线
					--print("22222")
					if Actor.canBeTelported( player ) == enCanntBeTeledReason_No then			--玩家能够被拉传
						local enterPos 	= CrossLeagueMatchesCfg.enterPos[side]
						if dVar.crossLeague[fubenIdx] and Actor.enterFuBen( player, dVar.crossLeague[fubenIdx], CrossLeagueMatchesCfg.sceneId, enterPos[1], enterPos[2]) then
							OpenCrossLeaguePanel( player )
							local fubenPtr = Fuben.getFubenPtr( dVar.crossLeague[fubenIdx] )
							if side == 1 then
								Fuben.setFbValue( fubenPtr, CROSS_LEAGUE_PlAYER1, playerId )
								Fuben.setFbValue( fubenPtr, CROSS_LEAGUE_SCORE1, 0 )			
								side = 2
							else
								Fuben.setFbValue( fubenPtr, CROSS_LEAGUE_PlAYER2, playerId )
								Fuben.setFbValue( fubenPtr, CROSS_LEAGUE_SCORE2, 0 )
								fubenIdx = fubenIdx + 1
								side = 1
							end

							local data = gRankMgr_GetValueById(playerId, RANK_CROSS_LEAGUE_SCORE, 1)
							local myData = BaseFuc_unserialize(data)

							if not myData then
								myData = {}
							end
							
							if not myData.name then
								myData.name = Actor.getName(player)
								myData.level = Actor.getIntProperty(player, PROP_CREATURE_LEVEL)
								myData.power = Actor.getIntProperty(player, PROP_ACTOR_BATTLE_POWER)
							end

							local times = CrossLeagueMatchesGetTimeIdx()

							if not myData.highCount then
								myData.highCount = CrossLeagueMatchesCfg.resetHighCount[times]
							end
							if not myData.lowCount then
								myData.lowCount = CrossLeagueMatchesCfg.resetLowCount[times]
							end
							myData.highFight = nil
							if myData.highCount and myData.highCount > 0 then
								myData.highCount = myData.highCount - 1
								myData.highFight = 1
							elseif myData.highCount and myData.highCount == -1 then
								myData.highFight = 1
							elseif myData.lowCount and myData.lowCount > 0 then
								myData.lowCount = myData.lowCount - 1
							end

							if myData.highFight then
								if not myData.highCountSet then
									myData.highCountSet = 0
								end
								myData.highCountSet = myData.highCountSet + 1
							else
								if not myData.lowCountSet then
									myData.lowCountSet = 0
								end
								myData.lowCountSet = myData.lowCountSet + 1
							end

						    if not myData.sex then
						        myData.sex = Actor.getIntProperty(player, PROP_ACTOR_SEX)
						        myData.vocation = Actor.getIntProperty(player, PROP_ACTOR_VOCATION)
						    end

							local newData = BaseFuc_serialize(myData)
							gRankMgr_SetRankEx(playerId, RANK_CROSS_LEAGUE_SCORE, 1, newData)
						else
							local isHighScore = false
							local data = gRankMgr_GetValueById(playerId, RANK_CROSS_LEAGUE_SCORE, 1)
							local myData = BaseFuc_unserialize(data)

							if not myData then
								myData = {}
							end
							
							if not myData.name then
								myData.name = Actor.getName(player)
								myData.level = Actor.getIntProperty(player, PROP_CREATURE_LEVEL)
								myData.power = Actor.getIntProperty(player, PROP_ACTOR_BATTLE_POWER)
							end

							local times = CrossLeagueMatchesGetTimeIdx()

							if not myData.highCount then
								myData.highCount = CrossLeagueMatchesCfg.resetHighCount[times]
							end
							if not myData.lowCount then
								myData.lowCount = CrossLeagueMatchesCfg.resetLowCount[times]
							end

							if myData.highCount and myData.highCount > 0 then
								myData.highCount = myData.highCount - 1
								isHighScore = true
							elseif myData.highCount and myData.highCount == -1 then
								isHighScore = true
							elseif myData.lowCount and myData.lowCount > 0 then
								myData.lowCount = myData.lowCount - 1
							end

							if isHighScore then
								if not myData.addScoreCountHigh then
									myData.addScoreCountHigh = 0
								end
								myData.addScoreCountHigh = myData.addScoreCountHigh + 1
							else
								if not myData.addScoreCountLow then
									myData.addScoreCountLow = 0
								end
								myData.addScoreCountLow = myData.addScoreCountLow + 1
							end

						    if not myData.sex then
						        myData.sex = Actor.getIntProperty(player, PROP_ACTOR_SEX)
						        myData.vocation = Actor.getIntProperty(player, PROP_ACTOR_VOCATION)
						    end

						    local newData = BaseFuc_serialize(myData)
							gRankMgr_SetRankEx(playerId, RANK_CROSS_LEAGUE_SCORE, 1, newData)

						    local socreReward
							if isHighScore then
						    	socreReward = CrossLeagueMatchesCfg.AddScore[1]
						    else
						    	socreReward = CrossLeagueMatchesCfg.AddScore[2]
						    end

    						local addScore = socreReward.passScore

    						local addAward = socreReward.passAward
    						if addAward and IsBagGridEnough(player, addAward) then
    							GiveCommonAward(player, addAward, LogIds.CrossLeagueMatchesLogId, Lang.LogTips.CrossLeagueMatches)
    						end
    
							gRankMgr_AddValue(playerId, RANK_CROSS_LEAGUE_SCORE, addScore)

							Actor.sendTipmsg(player, string.format(Lang.ScriptTips.CrossLeaguematches010, addScore), ttFlyTip)

							if myData.highCount and myData.lowCount and myData.highCount == 0 and myData.lowCount == 0 then
							else
								local mySignState
								if not IsCrossLeagueMatchesCanSign() then
									mySignState = 0
								else
									mySignState = 1
								end
								SendCrossLeagueSignStateChange(player, mySignState, 1)
							end
							
						end
					end
				end
			end
		end
	end
	gRankMgr_Clear(RANK_CROSS_LEAGUE_SIGN)
	if Lang.ScriptTips.CrossLeaguematches009 ~= "" then
		System.broadcastTipmsg( Lang.ScriptTips.CrossLeaguematches009, ttScreenCenter + ttChatWindow )
	end
end

--重置次数
function CrossLeagueMatchesResetCount(times)
	local myTimes = tonumber(times)
	local sVar = System.getStaticVar()
	sVar.crossLeagueMatchesResetIdx = myTimes
	if not IsCrossLeagueMatchesStart() then return end
	local rankPtr = Ranking.getRanking(RankList[RANK_CROSS_LEAGUE_SCORE].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	for idx = 1, rankCount do
		local item = Ranking.getItemFromIndex(rankPtr, idx-1)
		if item then
			local actorid = tonumber(Ranking.getId(item))
			local data = Ranking.getSub(item, 1)
			local myData
			if not data or data == "" then
				myData = {}
			else
				myData = BaseFuc_unserialize(data)
			end
			
			myData.highCount = CrossLeagueMatchesCfg.resetHighCount[myTimes]
			myData.lowCount = CrossLeagueMatchesCfg.resetLowCount[myTimes]

			local newData = BaseFuc_serialize(myData)
			gRankMgr_SetRankEx(actorid, RANK_CROSS_LEAGUE_SCORE, 1, newData)
		end
	end
end

--奖励可以领取
function CrossLeagueMatchesCalc()
	if not IsCrossLeagueMatchesStart() then return end
	local sVar = System.getStaticVar()
	sVar.crossLeagueMatchesStart = nil
	sVar.crossLeagueMatchesAward = 1
	sVar.crossLeagueMatchesSign = nil
	System.broadcastTipmsg( Lang.ScriptTips.CrossLeaguematches012, ttScreenCenter + ttChatWindow )
	local rankPtr = Ranking.getRanking(RankList[RANK_CROSS_LEAGUE_SCORE].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	for idx = 1, rankCount do
		local item = Ranking.getItemFromIndex(rankPtr, idx-1)
		if item then
			local actorid = tonumber(Ranking.getId(item))
			local player = Actor.getActorById(actorid)
			if player then
				local score = Ranking.getPoint(item)
				local myRank = idx
				if score < CrossLeagueMatchesCfg.MinRankScore then
					myRank = 0
				elseif myRank > CrossLeagueMatchesCfg.RankNum then
					myRank = 0
				end
				SendCrossLeagueRewardStateChange(player, 1, myRank)
			end
		end
	end
end

--领取状态改变
function SendCrossLeagueRewardStateChange(sysarg, state, myRank)
	local netPack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sCrossLeagueGetAward) 
  	if not netPack then return end
  	--print("myRank ="..myRank)
  	DataPack.writeByte(netPack, myRank or 0)
  	--print("state ="..state)
  	DataPack.writeByte(netPack, state or 0)
  	DataPack.flush(netPack)
end

--报名状态改变
function SendCrossLeagueSignStateChange(sysarg, state, needTip)
	local netPack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sCrossLeagueSign) 
  	if not netPack then return end
  	--print("state ="..state)
  	DataPack.writeByte(netPack, state or 0)
  	--print("needTip ="..needTip)
  	DataPack.writeByte(netPack, needTip or 0)
  	DataPack.flush(netPack)
end

--战斗结束通知
function SendCrossLeaguePKResult(sysarg, state, score, highState)
	local netPack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sCrossLeaguePkEnd) 
  	if not netPack then return end
  	--print("state ="..state)
  	DataPack.writeByte(netPack, state or 3)
  	--print("highState ="..highState)
  	DataPack.writeByte(netPack, highState or 2)
  	--print("score ="..score)
  	DataPack.writeInt(netPack, score or 0)
  	DataPack.flush(netPack)
end

--重生
function CrossLeagueMatchesRelive(sysarg, reliveType)
	local idx, pos = GetItemIdxRandNoWeight( CrossLeagueMatchesCfg.relivePos )
	if pos[1] > 0 and pos[2] > 0 then
		local fubenHandle = Actor.getFubenHandle( sysarg )
		Actor.enterFuBen( sysarg, fubenHandle, CrossLeagueMatchesCfg.sceneId, pos[1], pos[2] )
	end
end

function CrossLeagueMatchesOffLine(sysarg)
	if not IsCrossLeagueMatchesCanSign() then
		return
	end
	local actorid = Actor.getActorId(sysarg)
	local sign = gRankMgr_GetValue(actorid, RANK_CROSS_LEAGUE_SIGN)
	if sign > 0 then
		gRankMgr_RemoveItemById(actorid, RANK_CROSS_LEAGUE_SIGN)
		return
	end
end

--手动离开
function CrossLeagueMatchesLeaveActivity(sysarg)
	if not IsInCrossLeagueFuben(sysarg) then
		return
	end
	local fubenPtr = Actor.getFubenPrt( sysarg )

	local playerList = LuaHelp.getFbActorList(fubenPtr) or {}
	if #playerList == CROSS_LEAGUE_PLAYER_NUM then
		for i, player in ipairs( playerList or {} ) do
			if player == sysarg then
				CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_LOSE)
			else
				CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_WIN)
			end
			Actor.exitFuben(player)
		end
	elseif #playerList < CROSS_LEAGUE_PLAYER_NUM then
		for i, player in ipairs( playerList or {} ) do
			CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_WIN)
			Actor.exitFuben(player)
		end
	end

	local dVar = System.getDyanmicVar()
	if not dVar.crossLeague then
		dVar.crossLeague = {}
	end

	local crossLeagueIdx = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_IDX ) or 0
	if crossLeagueIdx > 0 then
		dVar.crossLeague[crossLeagueIdx] = nil
	end

	local fubenHandle 	= Fuben.getFubenHandle( fubenPtr )
	Fuben.setFubenTime( fubenHandle, 1 )
end

--死亡
function CrossLeagueMatchesActorDeath( sysarg, killerPtr )
	if not IsInCrossLeagueFuben(sysarg) then
		return
	end

	local fubenPtr = Actor.getFubenPrt( killerPtr )

	local playerList = LuaHelp.getFbActorList(fubenPtr) or {}
	--print("#playerList ="..#playerList)
	if #playerList ~= CROSS_LEAGUE_PLAYER_NUM then
		return
	end

	local PlayerId1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER1 ) or 0
	--local Score1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE1 ) or 0

	local PlayerId2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER2 ) or 0
	--local Score2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE2 ) or 0

	local killerId = Actor.getActorId(killerPtr)
	local fubenValueId
	if killerId == PlayerId1 then
		fubenValueId = CROSS_LEAGUE_SCORE1
	elseif killerId == PlayerId2 then
		fubenValueId = CROSS_LEAGUE_SCORE2
	end

	if not fubenValueId then
		return
	end

	local Score = Fuben.getFbValue( fubenPtr, fubenValueId ) or 0
	local newScore = Score + 1
	if newScore >= CrossLeagueMatchesCfg.deadOutCount then
		for i, player in ipairs( playerList or {} ) do
			if player == sysarg then
				CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_LOSE)
				Actor.returnCity( player )
			else
				CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_WIN)
				Actor.exitFuben( player )
			end
		end
		
		local dVar = System.getDyanmicVar()
		if not dVar.crossLeague then
			dVar.crossLeague = {}
		end

		local crossLeagueIdx = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_IDX ) or 0
		if crossLeagueIdx > 0 then
			dVar.crossLeague[crossLeagueIdx] = nil
		end

		local fubenHandle 	= Fuben.getFubenHandle( fubenPtr )
		Fuben.setFubenTime( fubenHandle, 1 )
	else
		Fuben.setFbValue( fubenPtr, fubenValueId, Score + 1 ) 		


		for i, player in ipairs( playerList or {} ) do
			ChangeCrossLeaguePanel( player )
		end
	end
end

--离开场景
function CrossLeagueMatchesLeaveActivityHandler(sysarg)
	CloseActivityRightPanel(sysarg)
end

--进入场景
function CrossLeagueMatchesEnterSceneHandler( sysarg, sceneId, lastSceneId )
	if not IsCrossLeagueMatchesCanSign() then
		return
	end
	local actorid = Actor.getActorId(sysarg)
	local sign = gRankMgr_GetValue(actorid, RANK_CROSS_LEAGUE_SIGN)
	if sign > 0 then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches008, ttFlyTip)
		gRankMgr_RemoveItemById(actorid, RANK_CROSS_LEAGUE_SIGN)
		return
	end
end

--请求数据
function SendCrossLeagueData(sysarg, packet)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	SendCrossLeagueDataSub(sysarg)
end
function SendCrossLeagueDataSub(sysarg)
	local rankPtr = Ranking.getRanking(RankList[RANK_CROSS_LEAGUE_SCORE].strName)
	local actorid = Actor.getActorId(sysarg)
	local myItem = Ranking.getItemPtrFromId(rankPtr, actorid)
	local myRank = 0
	local myScore = 0
	local myAwardState = 0
	local mySignState = 0
	local highCount = 0
	local lowCount = 0
	if myItem then
		myRank = Ranking.getIndexFromPtr(myItem) + 1
		myScore = Ranking.getPoint(myItem)
		if myScore < CrossLeagueMatchesCfg.MinRankScore then
			myRank = 0
		elseif myRank > CrossLeagueMatchesCfg.RankNum then
			myRank = 0
		end
		
		local data = Ranking.getSub(myItem, 1)
		local myData
		if not data or data == "" then
			myData = {}
		else
			myData = BaseFuc_unserialize(data)
		end

		local times = CrossLeagueMatchesGetTimeIdx()

		if not myData.highCount then
			myData.highCount = CrossLeagueMatchesCfg.resetHighCount[times]
		end

		highCount = myData.highCount

		if not myData.lowCount then
			myData.lowCount = CrossLeagueMatchesCfg.resetLowCount[times]
		end

		lowCount = myData.lowCount
		
		if ( not myData.myAwardState or myData.myAwardState == 0 ) and IsCrossLeagueMatchesCanGetAward() then
			myAwardState = 1
		else
			myAwardState = myData.myAwardState or 0
		end
	else
		local times = CrossLeagueMatchesGetTimeIdx()
		highCount = CrossLeagueMatchesCfg.resetHighCount[times]
		lowCount = CrossLeagueMatchesCfg.resetLowCount[times]
	end

	if not IsCrossLeagueMatchesCanSign() then
		mySignState = 0
	else
		local sign = gRankMgr_GetValue(actorid, RANK_CROSS_LEAGUE_SIGN)
		if sign > 0 then
			mySignState = 2
		else
			mySignState = 1
		end
	end

	local RankCount = Ranking.getRankItemCountByLimit(rankPtr, CrossLeagueMatchesCfg.MinRankScore)
	if RankCount > CrossLeagueMatchesCfg.RankNum then
		RankCount = CrossLeagueMatchesCfg.RankNum
	end

	local netPack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sCrossLeagueInit) 
  	if not netPack then return end

  	DataPack.writeByte(netPack, RankCount)
  	if RankCount > 0 then
		for idx = 1, RankCount do
			local item = Ranking.getItemFromIndex(rankPtr, idx-1)
			if item then
				local actorid = tonumber(Ranking.getId(item))
				local point = Ranking.getPoint(item)
				local data = Ranking.getSub(item, 1)
				local dataTable
				if not data or data == "" then
					dataTable = {}
				else
					dataTable = BaseFuc_unserialize(data)
				end
				DataPack.writeString(netPack, dataTable.name or "")
				--print("dataTable.name = "..dataTable.name)
				DataPack.writeShort(netPack, dataTable.level or 1)  
				--print("dataTable.level = "..dataTable.level)
				DataPack.writeInt(netPack, dataTable.power or 0)
				--print("dataTable.power = "..dataTable.power)
				DataPack.writeInt(netPack, point or 0)
				--print("point = "..point)
			end
		end
	end
	--print("myRank = "..myRank)
  	DataPack.writeByte(netPack, myRank or 0)
  	--print("myScore = "..myScore)
  	DataPack.writeInt(netPack, myScore or 0)
  	--print("highCount = "..highCount)
  	DataPack.writeByte(netPack, highCount or 0)
  	--print("lowCount = "..lowCount)
  	DataPack.writeShort(netPack, lowCount or 0)
  	--print("myAwardState = "..myAwardState)
  	DataPack.writeByte(netPack, myAwardState or 0)
  	--print("mySignState = "..mySignState)
  	DataPack.writeByte(netPack, mySignState or 0)
  	DataPack.flush(netPack)
end

--获取第几次reset
function CrossLeagueMatchesGetTimeIdx()
	local sVar = System.getStaticVar()
	if sVar.crossLeagueMatchesResetIdx then
		return sVar.crossLeagueMatchesResetIdx
	end
	local nHour,nMin,nSec = System.getTime(0,0,0,0)    --当前时间
	for idx = 1, #CrossLeagueMatchesCfg.activeTime do
		local time = CrossLeagueMatchesCfg.activeTime[idx]
		local timeBegin = time[1]
		local timeEnd 	= time[2]
		if timeBegin[1] == timeEnd[1]  then    		--起止小时是同一个小时
			if timeBegin[2] <= nMin and nMin < timeEnd[2] then	--不在分钟范围之内
				return idx
			end
		elseif timeBegin[1] < timeEnd[1] then		--开始小时小于结束小时
			if timeBegin[1] < nHour and nHour < timeEnd[1] then
				return idx
			elseif nHour == timeBegin[1] and timeBegin[2] <= nMin then
				return idx
			elseif nHour == timeEnd[1] and nMin < timeEnd[2] then
				return idx
			end
		end
	end
	return 1
end

--报名
function CrossLeagueSign(sysarg, packet)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	local opType = DataPack.readByte(packet)
	CrossLeagueSignSub(sysarg, opType)
end

function CrossLeagueSignSub(sysarg, opType)
	--print("CrossLeagueSignSub  opType ="..opType)
	if opType == 2 then
		if not IsCrossLeagueMatchesCanSign() then
			return
		end
		local actorid = Actor.getActorId(sysarg)
		local sign = gRankMgr_GetValue(actorid, RANK_CROSS_LEAGUE_SIGN)
		if sign > 0 then
			gRankMgr_RemoveItemById(actorid, RANK_CROSS_LEAGUE_SIGN)
			SendCrossLeagueSignStateChange(sysarg, 1, 0)
			return
		end
	else
		if not IsCrossLeagueMatchesCanSign() then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches003, ttFlyTip)
			return
		end

		local actorid = Actor.getActorId(sysarg)

		local sign = gRankMgr_GetValue(actorid, RANK_CROSS_LEAGUE_SIGN)
		if sign > 0 then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches004, ttFlyTip)
			return
		end

		local levelLimit = CrossLeagueMatchesCfg.levelLimit
		if not Actor.checkActorLevel( sysarg, levelLimit[2], levelLimit[1] ) then
	    	Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0016,ttFlyTip)
	    	return
	    end

		local data = gRankMgr_GetValueById(actorid, RANK_CROSS_LEAGUE_SCORE, 1)
		local myData = BaseFuc_unserialize(data)

		if not myData then
			myData = {}
		end
		
		myData.name = Actor.getName(sysarg)
		myData.level = Actor.getIntProperty(sysarg, PROP_CREATURE_LEVEL)
		myData.power = Actor.getIntProperty(sysarg, PROP_ACTOR_BATTLE_POWER)

		local times = CrossLeagueMatchesGetTimeIdx()

		if not myData.highCount then
			myData.highCount = CrossLeagueMatchesCfg.resetHighCount[times]
		end
		if not myData.lowCount then
			myData.lowCount = CrossLeagueMatchesCfg.resetLowCount[times]
		end

		if myData.highCount and myData.lowCount and myData.highCount == 0 and myData.lowCount == 0 then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches013,ttFlyTip)
			return
		end

	    if not myData.sex then
	        myData.sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
	        myData.vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
	    end

		local newData = BaseFuc_serialize(myData)
		gRankMgr_SetRankEx(actorid, RANK_CROSS_LEAGUE_SCORE, 1, newData)

		local score = gRankMgr_GetValue(actorid, RANK_CROSS_LEAGUE_SCORE)

		gRankMgr_SetRank(actorid, RANK_CROSS_LEAGUE_SIGN, score + 1)
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches005, ttFlyTip)

		SendCrossLeagueSignStateChange(sysarg, 2, 0)
	end
end

--领取奖励
function CrossLeagueGetAward(sysarg, packet)
	----[[
	if not Actor.IsCross(sysarg) then
		return
	end
	--]]
	CrossLeagueGetAwardSub(sysarg)
end

function CrossLeagueGetAwardSub(sysarg)
	if not IsCrossLeagueMatchesCanGetAward() then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches007, ttFlyTip)
		return
	end

	local rankPtr = Ranking.getRanking(RankList[RANK_CROSS_LEAGUE_SCORE].strName)
	local actorid = Actor.getActorId(sysarg)
	local myItem = Ranking.getItemPtrFromId(rankPtr, actorid)
	if myItem then
		local myRank = Ranking.getIndexFromPtr(myItem) + 1
		local myScore = Ranking.getPoint(myItem)
		if myScore < CrossLeagueMatchesCfg.MinRankScore then
			myRank = 0
		end

		local myRewards = GetElemByCond( CrossLeagueMatchesCfg.rankAwards, myRank )
		if not myRewards then
			--myRewards = CrossLeagueMatchesCfg.rankAwards[#CrossLeagueMatchesCfg.rankAwards]
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches014, ttFlyTip)
			return
		end

		local actorid = tonumber(Ranking.getId(myItem))
		local data = Ranking.getSub(myItem, 1)
		local myData
		if not data or data == "" then
			myData = {}
		else
			myData = BaseFuc_unserialize(data)
		end
		if myData.myAwardState and myData.myAwardState == 2 then
			Actor.sendTipmsg(sysarg, Lang.ScriptTips.CrossLeaguematches011, ttFlyTip)
			return
		end

		local myAward = myRewards.awards

		if myAward then
			if IsBagGridEnough(sysarg, myAward) then
				myData.myAwardState = 2
				local newData = BaseFuc_serialize(myData)
				gRankMgr_SetRankEx(actorid, RANK_CROSS_LEAGUE_SCORE, 1, newData)
				GiveCommonAward(sysarg, myAward, LogIds.CrossLeagueMatchesLogId, Lang.LogTips.CrossLeagueMatches)

				SendCrossLeagueRewardStateChange(sysarg, 2, myRank)
			else
				Actor.sendTipmsg(sysarg,Lang.ScriptTips.COM0015, ttFlyTip)
			end
		end
	end
end

--[[
副本时间到了
]]
function CrossLeagueMatchesTimeout( fubenPtr )
	local fubenId = Fuben.getFuBenId(fubenPtr)
	if fubenId ~= CrossLeagueMatchesCfg.fubenId then
		return
	end 

	local playerList = LuaHelp.getFbActorList(fubenPtr) or {}
	if #playerList == CROSS_LEAGUE_PLAYER_NUM then
		local PlayerId1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER1 ) or 0
		local Score1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE1 ) or 0

		local PlayerId2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER2 ) or 0
		local Score2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE2 ) or 0
		
		for i, player in ipairs( playerList or {} ) do
			if Actor.getActorId(player) == PlayerId1 then
				if Score1 > Score2 then
					CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_WIN)
				elseif Score1 < Score2 then
					CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_LOSE)
				else
					CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_DRAW)
				end	
			else
				if Score1 > Score2 then
					CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_LOSE)
				elseif Score1 < Score2 then
					CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_WIN)
				else
					CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_DRAW)
				end	
			end
			Actor.exitFuben(player)
		end
	elseif #playerList < CROSS_LEAGUE_PLAYER_NUM then
		for i, player in ipairs( playerList or {} ) do
			CrossLeagueMatchesAddScore(player, CROSS_LEAGUE_WIN)
			Actor.exitFuben(player)
		end
	end

	local dVar = System.getDyanmicVar()
	if not dVar.crossLeague then
		dVar.crossLeague = {}
	end

	local crossLeagueIdx = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_IDX ) or 0
	if crossLeagueIdx > 0 then
		dVar.crossLeague[crossLeagueIdx] = nil
	end
end

--积分增加
function CrossLeagueMatchesAddScore(sysarg, resultType)
	local actorid = Actor.getActorId(sysarg)
	local data = gRankMgr_GetValueById(actorid, RANK_CROSS_LEAGUE_SCORE, 1)
	local myData = BaseFuc_unserialize(data)

	if not myData then
		myData = {}
	end
	
	if not myData.name then
		myData.name = Actor.getName(sysarg)
		myData.level = Actor.getIntProperty(sysarg, PROP_CREATURE_LEVEL)
		myData.power = Actor.getIntProperty(sysarg, PROP_ACTOR_BATTLE_POWER)
	end

	local times = CrossLeagueMatchesGetTimeIdx()

	if not myData.highCount then
		myData.highCount = CrossLeagueMatchesCfg.resetHighCount[times]
	end
	if not myData.lowCount then
		myData.lowCount = CrossLeagueMatchesCfg.resetLowCount[times]
	end

    if not myData.sex then
        myData.sex = Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
        myData.vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
    end
    local socreReward
    local highState = 2
    if myData.highFight then
    	myData.highFight = nil
    	socreReward = CrossLeagueMatchesCfg.AddScore[1]
    	if not myData.addScoreCountHigh then
			myData.addScoreCountHigh = 0
		end
		myData.addScoreCountHigh = myData.addScoreCountHigh + 1
		highState = 1
    else
    	socreReward = CrossLeagueMatchesCfg.AddScore[2]
    	if not myData.addScoreCountLow then
			myData.addScoreCountLow = 0
		end
		myData.addScoreCountLow = myData.addScoreCountLow + 1
    end

    local newData = BaseFuc_serialize(myData)
	gRankMgr_SetRankEx(actorid, RANK_CROSS_LEAGUE_SCORE, 1, newData)

    local addScore 
    local addAward
    if resultType == CROSS_LEAGUE_WIN then
    	addScore = socreReward.winScore
    	addAward = socreReward.winAward
	elseif resultType == CROSS_LEAGUE_LOSE then
		addScore = socreReward.loseScore
		addAward = socreReward.loseAward
	elseif resultType == CROSS_LEAGUE_DRAW then
		addScore = socreReward.drawScore
		addAward = socreReward.drawAward
	end

	if addAward and IsBagGridEnough(sysarg, addAward) then
		GiveCommonAward(sysarg, addAward, LogIds.CrossLeagueMatchesLogId, Lang.LogTips.CrossLeagueMatches)
	end

	gRankMgr_AddValue(actorid, RANK_CROSS_LEAGUE_SCORE, addScore)

	SendCrossLeaguePKResult(sysarg, resultType, addScore, highState)

	if myData.highCount and myData.lowCount and myData.highCount == 0 and myData.lowCount == 0 then
		return
	end

	local mySignState
	if not IsCrossLeagueMatchesCanSign() then
		mySignState = 0
	else
		mySignState = 1
	end
	SendCrossLeagueSignStateChange(sysarg, mySignState, 1)
end

--左侧面板初始化
function OpenCrossLeaguePanel( sysarg )
	if not IsInCrossLeagueFuben( sysarg ) then
		--print("33333")
		return
	end
	local fubenPtr = Actor.getFubenPrt(sysarg)

	local activityType 	= 1 			--活动
	local activityId 	= enRightPanelActivity_CrossLeague
	local restTime 		= Fuben.getFbTime( fubenPtr )
	if restTime < 0 then
		restTime = 0
	end
	local panelInfo 	= {}
	panelInfo.sts 		= 1  									--进行中
	panelInfo.title 	= Lang.ScriptTips.CrossLeaguematchesPanel001
	panelInfo.timeTitle = Lang.ScriptTips.CrossLeaguematchesPanel002			--剩余时间
	panelInfo.restTime	= restTime


	local playerId1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER1 ) or 0 		--阵营1积分
	local score1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE1 ) or 0 		--阵营2积分

	local playerId2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER2 ) or 0 		--阵营1积分
	local score2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE2 ) or 0 		--阵营2积分

	panelInfo.contentTitle 	= ""  			--不用显示
	panelInfo.contents 		= {}


	if Actor.getActorId( sysarg ) == playerId1 then
		panelInfo.contents[1]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel003, score1 ) 		--本方积分
		panelInfo.contents[2]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel004, score2 )		--对方积分
	else
		panelInfo.contents[1]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel003, score2 )
		panelInfo.contents[2]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel004, score1 )
	end

	panelInfo.buttons   	= {}
	panelInfo.buttons[1]	= 1							--1：退出副本，2-单倍领奖，3-双倍领奖, 4-查看排行榜
	--panelInfo.buttons[2]	= 4	

	OpenActivityRightPanel( sysarg, activityType, activityId, panelInfo )
end

--左侧面板改变
function ChangeCrossLeaguePanel( sysarg )
	if not IsInCrossLeagueFuben( sysarg ) then
		return
	end

	local panelInfo 	= {}
	panelInfo.sts 		= 1
	panelInfo.contents 	= {}

	local fubenPtr = Actor.getFubenPrt(sysarg)

	local playerId1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER1 ) or 0 		--阵营1积分
	local score1 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE1 ) or 0 		--阵营2积分

	local playerId2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_PlAYER2 ) or 0 		--阵营1积分
	local score2 = Fuben.getFbValue( fubenPtr, CROSS_LEAGUE_SCORE2 ) or 0 		--阵营2积分


	if Actor.getActorId( sysarg ) == playerId1 then
		panelInfo.contents[1]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel003, score1 ) 		--本方积分
		panelInfo.contents[2]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel004, score2 )		--对方积分
	else
		panelInfo.contents[1]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel003, score2 )
		panelInfo.contents[2]	= string.format( Lang.ScriptTips.CrossLeaguematchesPanel004, score1 )
	end

	panelInfo.buttons   	= {}
	panelInfo.buttons[1]	= 1							--1：退出副本，2-单倍领奖，3-双倍领奖, 4-查看排行榜
	--panelInfo.buttons[2]	= 4

	ChangeActivityRightPanel( sysarg, panelInfo )
end

function gmTestRandomLst(sysarg, nStart, nEnd)
	local lstTable = GetCrossLeagueMatchesRandomNumber(nStart, nEnd)
	for idx = 1, #lstTable do
		print(lstTable[idx] .. " ")
	end
end

function gmCrossLeagueActive(sysarg, opType, data)
	if opType == 1 then
		SendCrossLeagueDataSub(sysarg)
	elseif opType == 2 then
		CrossLeagueSignSub(sysarg, data)
	elseif opType == 3 then
		CrossLeagueGetAwardSub(sysarg)
	end
end